package com.spark.market.common.interceptor;
import com.alibaba.fastjson.JSONObject;
import com.spark.market.api.utils.ResponseUtil;
import com.spark.market.common.constants.RedisCache;
import com.spark.market.common.exception.EmBusinessError;
import com.spark.market.common.utils.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class ApplicationInterceptor implements HandlerInterceptor{
    @Autowired
    private RedisUtil redis;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        MDC.put("marketId", UUID.randomUUID().toString());
        String userToken = request.getHeader("userToken");
        String userId = request.getHeader("userId");
//        request.getParameterMap("userId")[0];
        String redisToken = redis.get(RedisCache.USER_REDIS_SESSION + ":" + userId);
        if (StringUtils.isEmpty(redisToken)){//用户尚未登陆
            //注意此时如果抛出异常的话无法被捕获
//            throw new BusinessException(EmBusinessError.USER_NOT_LOGIN);
            returnErrorResponse(response,EmBusinessError.USER_NOT_LOGIN);
            return false;
        }else if (!userToken.equals(redisToken)){//用户在其它地方登陆
            returnErrorResponse(response, EmBusinessError.USER_LOGIN_ANYWHERE);
            return false;
        }
        return true;
    }

    public void returnErrorResponse(HttpServletResponse response,EmBusinessError error) throws IOException {
        OutputStream os = null;
        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/json");
            os = response.getOutputStream();
            Map<String,Object> responseData = new HashMap<>();
            responseData.put("errCode",error.getErrCode());
            responseData.put("errMsg",error.getErrMsg());
            os.write(JSONObject.toJSONBytes( ResponseUtil.createFailedResult(responseData,"fail")));
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (os != null){
                os.close();
            }
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        MDC.clear();
    }
}
